package ai.cultural;

import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

/**
 * 用简单UI演示用文化算法寻找最优解的过程
 */
public class DemoFrame extends Frame {

    private CulturalAlgorithm culturalAlgorithm;

    public DemoFrame(CulturalAlgorithm culturalAlgorithm) {
        this.culturalAlgorithm = culturalAlgorithm;

        this.setTitle("文化算法粒子位置动态显示");
        this.setSize(1000, 800);
        this.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
        this.setVisible(true);
    }

    public void paint(Graphics g) {
        g.setColor(new Color(0, 0, 0));
        g.setFont(new Font(null, Font.BOLD, 26));
        double[][] position = culturalAlgorithm.getPopulation();
        for (int i = 0; i < culturalAlgorithm.getPopulationSize(); i++) {
            g.drawString("☺", (int) (400 + position[0][i] * 80), (int) (400 + position[1][i] * 80));
            g.drawString("第【" + culturalAlgorithm.getCurrentGeneration() + "】代", 50, 650);
            g.drawString("当前最优点位置：" + position[0][0] + ", " + position[1][0], 50, 690);
            //g.drawString("当前最优值： " + func(position, 0), 50, 730);
        }

        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        g.setColor(new Color(255, 0, 0));
        g.setFont(new Font(null, Font.BOLD, 24));
        repaint();
    }

    public static void main(String[] args) {
        final CulturalAlgorithm culturalAlgorithm = new CulturalAlgorithm(50, 30, 2, 0.75,
                0.25, 1.25, new double[]{-5, -5}, new double[]{5, 5});
        new Thread(culturalAlgorithm::compute).start();
        new Thread(() -> new DemoFrame(culturalAlgorithm).repaint()).start();
    }
}
